var co = require('/resource/js/common.js')
var _this
App({
   Data: {
      userInfo: '',
      shopInfo: '',
      app: {
         appid: 'wxa97a45973f5f3774',
         secret: '0fb060068ac78a1e6591394dd6570ff4'
      },
   },
   //进入页面加载
   onLaunch(opt) {
      console.log('【onLaunch:opt】==', opt);
      this.do_opt_data(opt)
      _this = this
   },

   onShow(opt) {
      console.log('【onShow:opt】==', opt);
      this.do_opt_data(opt)
   },

   do_opt_data(opt) {
      // console.log('opt.referrerInfo====', !opt.referrerInfo)
      // console.log('opt.referrerInfo.extraData====', !opt.referrerInfo)
      if (!opt.referrerInfo)
         return

      if (!opt.referrerInfo.extraData)
         return

      this.do_opt_scene_data(opt.referrerInfo.extraData)
   },

   //微信登录授权
   wxLogin: function(callback) {
      wx.login({
         success: function(res) {
            _this.getWxSession(res.code, callback)
         },
         fail: function(res) {
            co.toastAllText("微信登录授权失败！")
         }
      })
   },
   //获取微信session_key保存起来，长时间有效可用
   getWxSession: function(code, callback) {
      co.getShareApi('api/Weixin/getSessionKey', {
         appid: _this.Data.app.appid,
         secret: _this.Data.app.secret,
         code: code,
         Users_ID: "jyhs"
      }, function(res) {
         if (res.code == 0) {
            var d = res.data
            wx.setStorageSync('session', d)
            if (typeof(callback) == 'function') {
               callback(d)
            }
         }
      })
   },

   //授权获取用户数据方法
   getWXUserInfo: function(callback) {
      wx.getUserInfo({
         withCredentials: true,
         lang: '',
         success: function(res) {
            console.log("【getWXUserInfo(callback)】success", res)
            _this.Data.isAuth = 1
            // _this.decryptWxInfoData(res, callback)
            _this.decryptWxUserInfoData(res, callback)
         },
         fail: function(res) {
            console.log("【getWXUserInfo(callback)】fail", res)
            _this.Data.isAuth = 0
         }
      })
   },

   //解密和获取微信用户信息
   decryptWxUserInfoData: function(data, callback, pageName, pagePath) {
      if (data.errMsg.indexOf('fail') != -1)
         return

      var param = {
         appid: this.Data.app.appid,
         session_key: wx.getStorageSync('session_key'),
         iv: data.iv,
         encryptedData: data.encryptedData,
      }

      if (data.User_Mobile) {
         param.User_Mobile = data.User_Mobile
      }
      if (wx.getStorageSync('Owner_Id')) {
         param.Owner_Id = wx.getStorageSync('Owner_Id')
         //console.log('【获取用户信息带上了要请人ID】==' + param.invite_id)
      }

      co.getShareApi('user/Mg/getInfo', param, function(res) {
         if (typeof(callback) == 'function') {
            callback(res)
         }
         if (res.code == 0) {
            _this.Data.userInfo = res.data
            console.log("【用户信息app】===", res.data)
            //保存用户信息
            wx.setStorageSync('userInfo', res.data)
         } else {
            if (res.code == 93748) {
               //解密失败可能是session__key失效了，需重新登录获取session__key
               _this.wxLogin()
            }
         }
      })
   },

   //解密和获取微信信息
   decryptWxInfoData: function(data, callback, pageName, pagePath) {
      if (data.errMsg.indexOf('fail') != -1)
         return

      var ss = wx.getStorageSync('session')
      var param = {
         appid: this.Data.app.appid,
         session_key: ss.session_key,
         iv: data.iv,
         encryptedData: data.encryptedData
      }
      console.log('decryptWxInfoData===', param);
      co.getShareApi('api/Weixin/decryptInfo', param, function(res) {
         if (res.code == 0) {
            if (typeof(callback) == 'function') {
               callback(res.data)
               return
            }
            if (pageName && pagePath)
               _this.forwardShare(res.data.openGId, pageName, pagePath)

         } else {
            _this.wxLogin() //解密失败可能是session_key失效了，需重新登录获取session_key
         }
      })
   },

   //获取分享信息
   getShareInfo: function(share_res, pageName, pagePath) {
      var shareTickets = share_res.shareTickets;
      if (!shareTickets || co.empty(shareTickets.length)) {
         _this.addShareCount(pageName)
         return false;
      }
      if (shareTickets.length == 0) {
         return false;
      }
      wx.getShareInfo({
         shareTicket: shareTickets[0],
         success: function(res) {
            console.log("【获取分享信息wx.getShareInfo】===", res)
            _this.decryptWxInfoData(res, '', pageName, pagePath)
         }
      })
   },
   //检查手机格式Verifying cell phone format
   checkPhoneFormat: function(phone) {
      var rule = /^1[0-9]{10}$/
      if (rule.test(phone)) {
         return 1
      }
      return 0
   },
   //保存转发分享
   forwardShare: function(gid, pageName, path) {
      var param = {
         User_ID: this.Data.userInfo.User_ID,
         Share_Page: pageName,
         Wx_Group_ID: gid,
         Share_Page_Path: path
      }
      co.getShareApi('share/Shmg/forwardShare', param, function(res) {
         console.log("【转发分享】", res.data)
         _this.addShareGroupCount(pageName)
      })
   },
   //处理scene参数，如：扫描进来的
   do_opt_scene_data: function(opt) {
      var param = {}
      if (opt.scene && opt.scene.indexOf(".") != -1) {
         var Arr = opt.scene.split('.')
         var len = Arr.length / 2
         for (var i = 0; i < len; i++) {
            var val_i = i * 2 + 1
            var key = Arr[val_i - 1]
            param[key] = Arr[val_i]
         }
      } else {
         param = opt
      }
      var old_opt = wx.getStorageSync('opt')
      console.log('old_opt=====', old_opt)
      console.log('param=======', param)
      old_opt = param
      // old_opt = co.addValueForKey(old_opt, param)
      wx.setStorageSync('opt', old_opt)
      return old_opt
   },
})